package com.kamistoat.meimeimall.meimeimallware.service.impl;

import com.kamistoat.meimeimall.common.utils.PageUtils;
import com.kamistoat.meimeimall.common.utils.Query;
import com.kamistoat.meimeimall.common.constant.WareConstant;
import com.kamistoat.meimeimall.meimeimallware.dao.PurchaseDetailDao;
import com.kamistoat.meimeimall.meimeimallware.entity.PurchaseDetailEntity;
import com.kamistoat.meimeimall.meimeimallware.service.PurchaseDetailService;
import com.kamistoat.meimeimall.meimeimallware.service.WareSkuService;
import com.kamistoat.meimeimall.meimeimallware.vo.MergeVo;
import com.kamistoat.meimeimall.meimeimallware.vo.PurchaseDetailStatusVo;
import com.kamistoat.meimeimall.meimeimallware.vo.PurchaseFinishVo;
import com.kamistoat.meimeimall.meimeimallware.dao.PurchaseDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.kamistoat.meimeimall.meimeimallware.entity.PurchaseEntity;
import com.kamistoat.meimeimall.meimeimallware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    PurchaseDetailDao purchaseDetailDao;
    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 自己编写的方法，获取新建/已分配的采购单
     *
     * @param params 查询参数
     * @return 分页封装
     */
    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", WareConstant.PurchaseStatus.CREATED.getCode()).
                        or().eq("status", WareConstant.PurchaseStatus.ASSIGNED.getCode()));
        return new PageUtils(page);
    }

    /**
     * 自己编写的方法，将采购需求合并成采购单
     *
     * @param mergeVo
     */
    @Override
    @Transactional
    public void mergePurchase(MergeVo mergeVo) {
        Long PurchaseId = 0L;
        if (mergeVo.getPurchaseId() == null) {
            // 没有指定采购单Id就先保存一个空采购单获取Id
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatus.CREATED.getCode());
            purchaseEntity.setWareId(mergeVo.getWareId());
            this.save(purchaseEntity);
            PurchaseId = purchaseEntity.getId();
        } else {
            // 指定了采购单id就用这个id
            PurchaseId = mergeVo.getPurchaseId();
            PurchaseEntity purchaseEntity = baseMapper.selectById(PurchaseId);
            purchaseEntity.setWareId(mergeVo.getWareId());
            this.updateById(purchaseEntity);
        }
        // 修改采购需求，绑定采购单
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = PurchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntityList = items.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatus.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailEntityList);
    }

    /**
     * 自己编写的方法，获取分配给自己的采购单
     *
     * @param assignee_name
     * @return
     */
    @Override
    @Transactional
    public List<Long> getASSIGNED(String assignee_name) {
        // 获取分配给自己的采购单
        List<PurchaseEntity> purchaseEntityList =
                baseMapper.selectList(new QueryWrapper<PurchaseEntity>().eq("assignee_name", assignee_name));
        List<Long> ASSIGNEDids = purchaseEntityList.stream().map(purchaseEntity -> {
            return purchaseEntity.getId();
        }).collect(Collectors.toList());
        return ASSIGNEDids;
    }

    /**
     * 自己编写的方法，提交采购员选择的采购单Ids
     *
     * @param purchaseIds 采购单Ids
     */
    @Override
    @Transactional
    public void postRECEIVED(List<Long> purchaseIds) {
        // 首先将采购单状态改为已领取
        List<PurchaseEntity> purchaseEntityList = baseMapper.selectBatchIds(purchaseIds);
        List<PurchaseEntity> purchaseEntities = purchaseEntityList.stream().map(purchaseEntity -> {
            purchaseEntity.setStatus(WareConstant.PurchaseStatus.RECEIVED.getCode());
            return purchaseEntity;
        }).collect(Collectors.toList());
        this.updateBatchById(purchaseEntities);
        // 再将采购单下的所有采购需求改为正在采购
        purchaseIds.forEach(purchaseId -> {
            List<PurchaseDetailEntity> purchaseDetailEntityList =
                    purchaseDetailDao.selectList(
                            new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", purchaseId));
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailEntityList.stream().map(purchaseDetailEntity -> {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatus.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(purchaseDetailEntities);
        });
    }

    /**
     * 自己方法，采购员完成采购单
     *
     * @param purchaseFinishVo Vo类
     */
    @Override
    @Transactional
    public void postFINISHED(PurchaseFinishVo purchaseFinishVo) {
        PurchaseEntity purchaseEntity = baseMapper.selectById(purchaseFinishVo.getPurchaseId());
        // 1 遍历采购需求的状态，更改采购需求的状态
        // 2 同时对完成的采购需求更新商品库存
        // 3 如果所有采购需求都成功，则采购单成功，否则采购单状态异常

        // 遍历采购需求
        List<PurchaseDetailStatusVo> pdsVoList = purchaseFinishVo.getPDSVoList();
        for (PurchaseDetailStatusVo pdsVo : pdsVoList) {
            // 首先都要把采购需求数据查出来
            PurchaseDetailEntity pDEntity = purchaseDetailService.getById(pdsVo.getPurchaseDetailId());
            if (pdsVo.getStatus().equals(WareConstant.PurchaseDetailStatus.FINISHED.getCode())) {
                // 如果成功，先更改采购需求状态
                pDEntity.setStatus(WareConstant.PurchaseDetailStatus.FINISHED.getCode());
                // 再修改对应商品库存，因为逻辑有点复杂所以不在这里处理
                wareSkuService.addStock(pDEntity.getSkuId(),pDEntity.getWareId(),pDEntity.getSkuNum());
                purchaseDetailDao.updateById(pDEntity);
            } else{
                // 否则更改采购需求，并设置标志位声明采购单状态
                purchaseEntity.setStatus(WareConstant.PurchaseStatus.HASERROR.getCode());
                pDEntity.setStatus(WareConstant.PurchaseDetailStatus.HASERROR.getCode());
                purchaseDetailDao.updateById(pDEntity);
            }
        }
        // 保存采购单
        baseMapper.updateById(purchaseEntity);
    }

}